package com.zhoukai.exception;

import com.zhoukai.vo.AjaxResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author Mr.ZHOU
 * @Date Created in 2021/12/21 17:00
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 如果前端是使用json对象进行传参，。那屋么如果验证不通过，会触发这个MethodArgumentNotValidException异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public AjaxResult jsonErrorHandler(MethodArgumentNotValidException  e){
        return getAjaxResult(e.getBindingResult());
    }

    /**
     * 如果前端提交的是路径参数  127.0.0.1?admin=123&password=123456
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BindException.class})
    public AjaxResult paramsErrorHandler(BindException  e){
        return getAjaxResult(e.getBindingResult());
    }


    private AjaxResult getAjaxResult(BindingResult bindingResult){
        List<Map<String,Object>> list=new ArrayList<>();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError allError : allErrors) {
            Map<String,Object> map=new HashMap<>();
            map.put("defaultMessage",allError.getDefaultMessage());
            map.put("objectName",allError.getObjectName());
            //注意，这里面拿到具体的某一个属性
            FieldError fieldError= (FieldError) allError;
            map.put("field",fieldError.getField());
            list.add(map);
        }
        return AjaxResult.fail("后端数据校验异常",list);
    }
}
